package com.gitee.netty.netty_demo;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 开发人员   YooLin1c
 * 编写日期   2018/7/21
 * 联系邮箱   401664157@qq.com
 * 作用描述
 */
@Slf4j
public class ServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("channel active");
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        log.info("handler added");
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        log.info("channel registered");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);

        new Thread(() -> {
            // 耗时的操作
            String result = loadFromDB();
            ctx.channel().writeAndFlush(result);
            ctx.executor().schedule(() -> {
                // ...
            }, 1, TimeUnit.SECONDS);
        }).start();
    }

    private String loadFromDB() {
        return "hello netty";
    }
}
